<?php
namespace App\Admin\Controllers\ZiNiao;

use App\Models\ZiNiao\PlansTasks;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use App\Admin\Ajax\ZiNiao\PlansTasksAjax;
class PlansTasksController extends AdminController{

    protected $title = 'RPA任务查询';

    protected $filters = [
        'planId' => null,
        'taskId' => null,
        'planStatus' => null,
        'taskStatus' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['planId'] = $this->filters['planId'];
        $filtersBlade['taskId'] = $this->filters['taskId'];
        $filtersBlade['planStatus'] = getOptions(PlansTasks::$_planStatus,$this->filters['planStatus']);
        $filtersBlade['taskStatus'] = getOptions(PlansTasks::$_taskStatus,$this->filters['taskStatus']);
        $filtersBlade['status'] = getOptions(PlansTasks::$_status,$this->filters['status']);
        return view('ziniao.plans-tasks.index', compact('paginator','action','filtersBlade'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = PlansTasks::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if(in_array($field,['planId','taskId','planStatus','taskStatus','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",20)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new PlansTasksAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
